package oa.hleast.xswl.controller.app.questionnaire;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.enums.QueryModeEnum;
import oa.hleast.common.result.Result;
import oa.hleast.common.result.ResultCode;
import oa.hleast.common.web.util.RequestUtils;
import oa.hleast.xswl.pojo.domain.questionnaire.QmsQuestionnaire;
import oa.hleast.xswl.pojo.domain.questionnaire.QmsUserQuestionnaireState;
import oa.hleast.xswl.pojo.form.questionnaire.UserQuestionnaireForm;
import oa.hleast.xswl.pojo.vo.ShowQuestionnaireVo;
import oa.hleast.xswl.pojo.vo.questionnaire.QmsSubmitQuestionnaireResponseVo;
import oa.hleast.xswl.pojo.vo.questionnaire.QmsSubmitQuestionnaireVo;
import oa.hleast.xswl.pojo.vo.questionnaire.UserQuestionnaireStateResultVo;
import oa.hleast.xswl.service.questionnaire.QmsQuestionnaireService;
import oa.hleast.xswl.service.questionnaire.QmsUserQuestionnaireStateService;
import oa.hleast.xswl.service.questionnaire.QuestionnaireService;
import oa.hleast.xswl.service.questionnaire.UserQuestionnaireService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Api(tags = "【移动端】答题模块问卷管理")
@RestController("AppQuestionnaireController")
@RequestMapping("/api.app/v1/questionnaires")
@Slf4j
@AllArgsConstructor
public class QuestionnaireController {

    private final QuestionnaireService questionnaireService;
    private final UserQuestionnaireService userQuestionnaireService;

    @Autowired
    private QmsUserQuestionnaireStateService qmsUserQuestionnaireStateService;

    @Autowired
    private QmsQuestionnaireService qmsQuestionnaireService;

    /**
     * 获取抗压力测试问卷及试题
     */
    public Result getAntiStressQuestionnaire(Long questionnaireId) {
        ShowQuestionnaireVo vo = questionnaireService.getAntiStressQuestionnaire(questionnaireId);
        return Result.success(vo);
    }

    @ApiOperation(value = "获取测试问卷及试题及答案", httpMethod = "GET")
    @GetMapping("/obtain/{questionnaireId}")
    public Result obtain(@PathVariable("questionnaireId") Long questionnaireId) {
        return getAntiStressQuestionnaire(questionnaireId);
    }


    /**
     * 提交压力测试问卷试题及答案
     */
    @ApiOperation(value = "提交测试问卷试题及答案", httpMethod = "POST")
    @ApiImplicitParam(name = "from", value = "实体JSON对象", required = true, paramType = "body", dataType = "UserQuestionnaireForm", dataTypeClass = UserQuestionnaireForm.class)
    @PostMapping
    public Result add(@RequestBody UserQuestionnaireForm form) {

        return sendUserQuestionnaire(form);
    }


    /**
     * 提交压力测试问卷试题及答案
     */
    public Result sendUserQuestionnaire(UserQuestionnaireForm form) {
        // 校验userId 使用注解
        QmsSubmitQuestionnaireResponseVo userTotalScore = userQuestionnaireService.sendUserQuestionnaire(form);

        return Result.success(userTotalScore);
    }

    @ApiOperation(value = "APP试卷列表分页", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "queryMode", paramType = "query", dataType = "QueryModeEnum", dataTypeClass = QueryModeEnum.class),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "limit", value = "每页数量", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "questionnaireContent", value = "问卷标识", paramType = "query", dataType = "String", dataTypeClass = String.class),
    })
    @GetMapping("/appQuestionnaireList")
    public Result appQuestionnaireList(
            String queryMode,
            Integer page,
            Integer limit,
            String questionnaireContent
    ) {
        List<QmsQuestionnaire> questionnaireContentList = null;
        QueryModeEnum queryModeEnum = QueryModeEnum.getValue(queryMode);
        switch (queryModeEnum) {
            case PAGE:
                LambdaQueryWrapper<QmsQuestionnaire> queryWrapper = new LambdaQueryWrapper<QmsQuestionnaire>()
                        .eq(StrUtil.isNotBlank(questionnaireContent), QmsQuestionnaire::getDisplay, Integer.valueOf(questionnaireContent))
                        .orderByDesc(QmsQuestionnaire::getGmtModified)
                        .orderByDesc(QmsQuestionnaire::getGmtCreate);
                Page<QmsQuestionnaire> result = qmsQuestionnaireService.page(new Page<>(page, limit), queryWrapper);
                List<QmsQuestionnaire> records = result.getRecords();
                /*records.forEach(x->{
                    String questionnaireContents = x.getTitle();
                    questionnaireContentList.add(questionnaireContents);
                });*/
                questionnaireContentList = qmsQuestionnaireService.list();
                return Result.success(questionnaireContentList, result.getTotal());
            default:
                return Result.failed(ResultCode.QUERY_MODE_IS_NULL);
        }
    }

    @ApiOperation(value = "APP试卷已完成列表分页", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "queryMode", paramType = "query", dataType = "QueryModeEnum", dataTypeClass = QueryModeEnum.class),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "limit", value = "每页数量", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
    })
    @GetMapping("/appCompletedQuestionnaireStateList")
    public Result appCompletedQuestionnaireStateList(
            String queryMode,
            Integer page,
            Integer limit
    ) {
        /*Long userId = RequestUtils.getUserId();
        userId=22L;

        List<UserQuestionnaireStateResultVo> userQuestionnaireStateResultVoList=new ArrayList<>();

        List<QmsUserQuestionnaireState> list = qmsUserQuestionnaireStateService.list(new LambdaQueryWrapper<QmsUserQuestionnaireState>().eq(QmsUserQuestionnaireState::getUserId, userId));
        for (QmsUserQuestionnaireState qmsUserQuestionnaireState : list) {
            Long userQuestionnaireId = qmsUserQuestionnaireState.getUserQuestionnaireId();
            UserQuestionnaireStateResultVo userQuestionnaireStateResultVo=new UserQuestionnaireStateResultVo();
            QmsQuestionnaire qmsQuestionnaire = qmsQuestionnaireService.getOne(new LambdaQueryWrapper<QmsQuestionnaire>().eq(QmsQuestionnaire::getId, userQuestionnaireId));
            BeanUtils.copyProperties(qmsQuestionnaire,userQuestionnaireStateResultVo,"id");
            userQuestionnaireStateResultVo.setUserTotalScore(qmsUserQuestionnaireState.getUserTotalScore());
            userQuestionnaireStateResultVoList.add(userQuestionnaireStateResultVo);
        }
        return Result.success(userQuestionnaireStateResultVoList);*/

        Long userId = RequestUtils.getUserId();
        List<UserQuestionnaireStateResultVo> userQuestionnaireStateResultVoList = new ArrayList<>();
        QueryModeEnum queryModeEnum = QueryModeEnum.getValue(queryMode);
        switch (queryModeEnum) {
            case PAGE:
                LambdaQueryWrapper<QmsUserQuestionnaireState> queryWrapper = new LambdaQueryWrapper<QmsUserQuestionnaireState>()
                        .eq( QmsUserQuestionnaireState::getUserId, userId)
                        .orderByDesc(QmsUserQuestionnaireState::getGmtModified)
                        .orderByDesc(QmsUserQuestionnaireState::getGmtCreate);
                Page<QmsUserQuestionnaireState> result = qmsUserQuestionnaireStateService.page(new Page<>(page, limit), queryWrapper);
                List<QmsUserQuestionnaireState> list = qmsUserQuestionnaireStateService.list(new LambdaQueryWrapper<QmsUserQuestionnaireState>().eq(QmsUserQuestionnaireState::getUserId, userId));
                list.forEach(qmsUserQuestionnaireState -> {
                    Long userQuestionnaireId = qmsUserQuestionnaireState.getUserQuestionnaireId();
                    QmsQuestionnaire qmsQuestionnaire = qmsQuestionnaireService.getById(userQuestionnaireId);
                    UserQuestionnaireStateResultVo userQuestionnaireStateResultVo=new UserQuestionnaireStateResultVo();
                    userQuestionnaireStateResultVo.setId(qmsUserQuestionnaireState.getUserQuestionnaireId());
                    userQuestionnaireStateResultVo.setTitle(qmsQuestionnaire.getTitle());
                    userQuestionnaireStateResultVo.setDisplay(qmsQuestionnaire.getDisplay());
                    userQuestionnaireStateResultVo.setPictureAddress(qmsQuestionnaire.getPictureAddress());
                    userQuestionnaireStateResultVo.setIntroduce(qmsQuestionnaire.getIntroduce());
                    userQuestionnaireStateResultVo.setUserTotalScore(qmsUserQuestionnaireState.getUserTotalScore());

                    userQuestionnaireStateResultVoList.add(userQuestionnaireStateResultVo);
                });
                return Result.success(userQuestionnaireStateResultVoList, result.getTotal());
            default:
                return Result.failed(ResultCode.QUERY_MODE_IS_NULL);
        }
    }

    @ApiOperation(value = "APP试卷未完成列表分页", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "queryMode", paramType = "query", dataType = "QueryModeEnum", dataTypeClass = QueryModeEnum.class),
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "limit", value = "每页数量", paramType = "query", dataType = "Long", dataTypeClass = Long.class),
    })
    @GetMapping("/appUnfinishedQuestionnaireStateList")
    public Result appUnfinishedQuestionnaireStateList(
            String queryMode,
            Integer page,
            Integer limit
    ) {
        Long userId = RequestUtils.getUserId();
        List<QmsQuestionnaire> qmsQuestionnaireList = qmsQuestionnaireService.list();
        /*Set<Long> userQuestionnaireIdList=null;
        List<QmsQuestionnaire> qmsQuestionnaireList = qmsQuestionnaireService.list();

        List<QmsUserQuestionnaireState> qmsCompletedUserQuestionnaireStateList= qmsUserQuestionnaireStateService.list(
                new LambdaQueryWrapper<QmsUserQuestionnaireState>().eq(QmsUserQuestionnaireState::getUserId, userId));
        for (QmsUserQuestionnaireState qmsUserQuestionnaireState : qmsCompletedUserQuestionnaireStateList) {
            Long userQuestionnaireId = qmsUserQuestionnaireState.getUserQuestionnaireId();

            qmsQuestionnaireList.forEach(qmsQuestionnaire -> {
                if(qmsQuestionnaire.getId().equals(userQuestionnaireId)){
                    qmsQuestionnaireList.remove(qmsQuestionnaire);
                }
            });
            userQuestionnaireIdList.add(userQuestionnaireId);
        }

        return Result.success(qmsQuestionnaireList);*/

        // List<QmsUserQuestionnaireState> qmsUserQuestionnaireStateList = null;


        QueryModeEnum queryModeEnum = QueryModeEnum.getValue(queryMode);
        switch (queryModeEnum) {
            case PAGE:
                LambdaQueryWrapper<QmsQuestionnaire> queryWrapper = new LambdaQueryWrapper<QmsQuestionnaire>()
                        .orderByDesc(QmsQuestionnaire::getGmtModified)
                        .orderByDesc(QmsQuestionnaire::getGmtCreate);
                Page<QmsQuestionnaire> result = qmsQuestionnaireService.page(new Page<>(page, limit), queryWrapper);

                List<QmsUserQuestionnaireState> qmsUserQuestionnaireStateList = qmsUserQuestionnaireStateService.list(
                        new LambdaQueryWrapper<QmsUserQuestionnaireState>().eq(QmsUserQuestionnaireState::getUserId,userId)
                );

                if(qmsUserQuestionnaireStateList!=null){
                    for (int i = 0; i < qmsQuestionnaireList.size(); i++) {
                        Long qmsQuestionnaireId = qmsQuestionnaireList.get(i).getId();
                        for (int j = 0; j < qmsUserQuestionnaireStateList.size(); j++) {
                            if(qmsUserQuestionnaireStateList.get(j).getUserQuestionnaireId().equals(qmsQuestionnaireId)){
                                qmsQuestionnaireList.remove(qmsQuestionnaireList.get(i));
                                i--;
                                break;
                            }
                        }
                    }
                    /*qmsQuestionnaireList.forEach(qmsQuestionnaire -> {
                        Long qmsQuestionnaireId = qmsQuestionnaire.getId();
                        for (QmsUserQuestionnaireState qmsUserQuestionnaireState : qmsUserQuestionnaireStateList) {
                            if(qmsUserQuestionnaireState.getUserQuestionnaireId().equals(qmsQuestionnaireId)){
                                qmsQuestionnaireList.remove(qmsQuestionnaire);
                            }
                        }
                    });*/
                }
                return Result.success(qmsQuestionnaireList, result.getTotal());
            default:
                return Result.failed(ResultCode.QUERY_MODE_IS_NULL);
        }
    }
}

